package com.fc.happyteam.api;

import com.fc.happyteam.common.ConverterUtil;
import com.fc.happyteam.common.ResponseJson;
import com.fc.happyteam.common.convert.BoatConverter;
import com.fc.happyteam.dto.BoatDto;
import com.fc.happyteam.entity.BoatEntity;
import com.fc.happyteam.entity.SkuPriceEntity;
import com.fc.happyteam.service.IBoatService;
import com.fc.happyteam.utils.DateUtils;
import com.fc.happyteam.utils.PageUtils;
import com.fc.happyteam.utils.Query;
import com.fc.happyteam.utils.R;
import com.fc.happyteam.utils.validator.ValidatorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by futurecreative on 2017/7/19.
 */
@RestController
@RequestMapping("/api/boat")
public class BoatController {

    @Autowired
    private IBoatService boatService;

    /**
     * 船列表
     */
    @RequestMapping("/list")
    public ResponseJson list(@RequestParam Map<String, Object> params){
        ResponseJson responseJson = new ResponseJson();

        //查询列表数据
        Query query = new Query(params);
        List<BoatEntity> boatList = boatService.queryList(query);
        int total = boatService.queryTotal(query);
        List<BoatDto> boatDtoList = ConverterUtil.convertList(BoatDto.class, boatList, BoatConverter.class);
        PageUtils pageUtil = new PageUtils(boatDtoList, total, query.getLimit(), query.getPage());
        responseJson.setObj(pageUtil);

        return responseJson;
    }

    /**
     * 船信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
        BoatEntity boat = boatService.getBoat(id);
        BoatDto boatDto = ConverterUtil.convert(boat, BoatDto.class, BoatConverter.class);
        return R.ok().put("boat", boatDto);
    }

    /**
     * 保存船
     */
    @RequestMapping("/save")
    public R save(@RequestBody BoatDto boatDto) {
        BoatEntity boat = ConverterUtil.convert(boatDto, BoatEntity.class, BoatConverter.class);
        int now = DateUtils.getEpochTimeInSecond(new Date());
        boat.setCreateDate(now);
        boat.setUpdateDate(now);
        ValidatorUtils.validateEntity(boat);
        if(boat.getPriceList() != null){
            for(SkuPriceEntity skuPrice : boat.getPriceList()){
                ValidatorUtils.validateEntity(skuPrice);
            }
        }
        boatService.save(boat);
        return R.ok();
    }

    /**
     * 删除船信息
     */
    @RequestMapping("/delete/{id}")
    public R delete(@PathVariable("id") Long id){
        boatService.delete(id);
        return R.ok();
    }
}
